﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Model;
using System.Text.Json;
namespace Admin.NET.Application;

/// <summary>
/// 系统出库单表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class SysoutstockorderService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Sysoutstockorder> _sysoutstockorderRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SysoutstockorderService(SqlSugarRepository<Sysoutstockorder> sysoutstockorderRep, ISqlSugarClient sqlSugarClient)
    {
        _sysoutstockorderRep = sysoutstockorderRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询系统出库单表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询系统出库单表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SysoutstockorderOutput>> Page(PageSysoutstockorderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _sysoutstockorderRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Code.Contains(input.Keyword) || u.OutType.Contains(input.Keyword) || u.WarehouseName.Contains(input.Keyword) || u.RelatedCode.Contains(input.Keyword) || u.CustomerName.Contains(input.Keyword) || u.ContactPerson.Contains(input.Keyword) || u.ContactMethod.Contains(input.Keyword) || u.GoodsName.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OutType), u => u.OutType.Contains(input.OutType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarehouseName), u => u.WarehouseName.Contains(input.WarehouseName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.RelatedCode), u => u.RelatedCode.Contains(input.RelatedCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), u => u.CustomerName.Contains(input.CustomerName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactPerson), u => u.ContactPerson.Contains(input.ContactPerson.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactMethod), u => u.ContactMethod.Contains(input.ContactMethod.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), u => u.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.DocumentStatus.HasValue, u => u.DocumentStatus == input.DocumentStatus.Value)
            .WhereIF(input.OutDateRange?.Length == 2, u => u.OutDate >= input.OutDateRange[0] && u.OutDate <= input.OutDateRange[1])
            .WhereIF(input.OutQuantity != null, u => u.OutQuantity == input.OutQuantity)
            .WhereIF(input.OutbouAmount != null, u => u.OutbouAmount == input.OutbouAmount)
            .WhereIF(input.DeleteTimeRange?.Length == 2, u => u.DeleteTime >= input.DeleteTimeRange[0] && u.DeleteTime <= input.DeleteTimeRange[1])
            .Select<SysoutstockorderOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取系统出库单表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取系统出库单表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Sysoutstockorder> Detail([FromQuery] QueryByIdSysoutstockorderInput input)
    {
        return await _sysoutstockorderRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加系统出库单表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加系统出库单表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost, UnitOfWork]
    public async Task<long> Add(AddSysoutstockorderInput input)
    {
        var entity = input.Adapt<Sysoutstockorder>();
        var result = await _sysoutstockorderRep.InsertAsync(entity);
        
        if (result && entity.WarePlaceId.HasValue && !string.IsNullOrWhiteSpace(input.GoodsName))
        {
            // 更新库位商品数据（出库）
            await UpdateWarePlaceGoods(entity);
        }
        
        return result ? entity.Id : 0;
    }
    
    /// <summary>
    /// 更新库位商品数据（出库）
    /// </summary>
    private async Task UpdateWarePlaceGoods(Sysoutstockorder order)
    {
        try
        {
            // 如果没有库位ID，跳过
            if (!order.WarePlaceId.HasValue) return;
            
            // 查找对应的库位
            var warePlace = await _sqlSugarClient.Queryable<WarePlaceModel>()
                .Where(x => x.Id == order.WarePlaceId.Value && !x.IsDelete)
                .FirstAsync();
            
            if (warePlace == null) return;
            
            // 检查库位是否已有商品数据
            List<WarePlaceGoods> goodsList = new List<WarePlaceGoods>();
            
            if (!string.IsNullOrWhiteSpace(warePlace.ShopName))
            {
                try
                {
                    var options = new JsonSerializerOptions
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                        PropertyNameCaseInsensitive = true
                    };
                    goodsList = JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName, options) ?? new List<WarePlaceGoods>();
                }
                catch
                {
                    goodsList = new List<WarePlaceGoods>();
                }
            }
            
            // 查找要出库的商品
            var existingGoods = goodsList.FirstOrDefault(g => g.GoodsName == order.GoodsName);
            if (existingGoods != null)
            {
                // 减少数量和金额
                existingGoods.Quantity -= order.OutQuantity;
                existingGoods.Amount -= order.OutbouAmount;
                
                // 更新单价（如果数量大于0）
                if (existingGoods.Quantity > 0)
                {
                    existingGoods.UnitPrice = existingGoods.Amount / existingGoods.Quantity;
                }
                else
                {
                    existingGoods.UnitPrice = 0;
                }
                
                existingGoods.UpdateTime = DateTime.Now;
                
                // 如果数量为0或负数，移除该商品
                if (existingGoods.Quantity <= 0)
                {
                    goodsList.Remove(existingGoods);
                }
            }
            
            // 将整个列表序列化并保存
            var serializeOptions = new JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                WriteIndented = false
            };
            var newShopName = JsonSerializer.Serialize(goodsList, serializeOptions);
            
            // 直接更新库位
            await _sqlSugarClient.Updateable<WarePlaceModel>()
                .SetColumns(it => new WarePlaceModel { ShopName = newShopName })
                .Where(it => it.Id == order.WarePlaceId.Value)
                .ExecuteCommandAsync();
        }
        catch (Exception ex)
        {
            // 记录错误但不影响出库操作
            Console.WriteLine($"更新库位商品数据失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 更新系统出库单表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新系统出库单表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSysoutstockorderInput input)
    {
        var entity = input.Adapt<Sysoutstockorder>();
        await _sysoutstockorderRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除系统出库单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除系统出库单表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSysoutstockorderInput input)
    {
        var entity = await _sysoutstockorderRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _sysoutstockorderRep.FakeDeleteAsync(entity);   //假删除
        //await _sysoutstockorderRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除系统出库单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除系统出库单表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSysoutstockorderInput> input)
    {
        var exp = Expressionable.Create<Sysoutstockorder>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _sysoutstockorderRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _sysoutstockorderRep.FakeDeleteAsync(list);   //假删除
        //return await _sysoutstockorderRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出系统出库单表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出系统出库单表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSysoutstockorderInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSysoutstockorderOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "系统出库单表导出记录");
    }
    
    /// <summary>
    /// 下载系统出库单表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载系统出库单表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSysoutstockorderOutput>(), "系统出库单表导入模板");
    }
    
    private static readonly object _sysoutstockorderImportLock = new object();
    /// <summary>
    /// 导入系统出库单表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入系统出库单表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_sysoutstockorderImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportSysoutstockorderInput, Sysoutstockorder>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.DocumentStatus == null){
                            x.Error = "单据状态不能为空";
                            return false;
                        }
                        if (x.OutQuantity == null){
                            x.Error = "出库数量不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Sysoutstockorder>>();
                    
                    var storageable = _sysoutstockorderRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Code), "出库单号不能为空")
                        .SplitError(it => it.Item.Code?.Length > 64, "出库单号长度不能超过64个字符")
                        .SplitError(it => it.Item.OutType?.Length > 32, "出库类型长度不能超过32个字符")
                        .SplitError(it => it.Item.WarehouseName?.Length > 64, "仓库名称长度不能超过64个字符")
                        .SplitError(it => it.Item.RelatedCode?.Length > 64, "关联单号长度不能超过64个字符")
                        .SplitError(it => it.Item.CustomerName?.Length > 128, "客户名称长度不能超过128个字符")
                        .SplitError(it => it.Item.ContactPerson?.Length > 64, "联系人长度不能超过64个字符")
                        .SplitError(it => it.Item.ContactMethod?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.GoodsName?.Length > 512, "出库货品长度不能超过512个字符")
                        .SplitError(it => it.Item.Remark?.Length > 512, "备注长度不能超过512个字符")
                        .SplitInsert(_=> true) // 没有设置唯一键代表插入所有数据
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.Code,
                        it.OutType,
                        it.DocumentStatus,
                        it.OutDate,
                        it.WarehouseName,
                        it.RelatedCode,
                        it.CustomerName,
                        it.ContactPerson,
                        it.ContactMethod,
                        it.GoodsName,
                        it.OutQuantity,
                        it.OutbouAmount,
                        it.Remark,
                        it.DeleteTime,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
